package com.power.using.mybomb.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.ViewPager;

import com.orhanobut.logger.Logger;
import com.power.using.mybomb.R;
import com.power.using.mybomb.adapter.ChatAdapter;
import com.power.using.mybomb.adapter.OnRecyclerViewListener;
import com.power.using.mybomb.base.ParentWithNaviActivity;
import com.power.using.mybomb.util.Util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMAudioMessage;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.core.BmobIMClient;
import cn.bmob.newim.core.BmobRecordManager;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.newim.listener.MessageListHandler;
import cn.bmob.newim.listener.MessageSendListener;
import cn.bmob.newim.listener.MessagesQueryListener;
import cn.bmob.newim.listener.OnRecordChangeListener;
import cn.bmob.newim.notification.BmobNotificationManager;
import cn.bmob.v3.exception.BmobException;

/**
 * Created by 聪明一只哈 on 2020/3/21.
 * Time: 2020/3/21  9:03
 */
public class ChatActivity extends ParentWithNaviActivity implements MessageListHandler {


    @BindView(R.id.v_top)
    View vTop;
    @BindView(R.id.tv_left)
    ImageView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.rc_view)
    RecyclerView rcView;
    @BindView(R.id.sw_refresh)
    SwipeRefreshLayout swRefresh;
    @BindView(R.id.iv_record)
    ImageView ivRecord;
    @BindView(R.id.tv_voice_tips)
    TextView tvVoiceTips;
    @BindView(R.id.layout_record)
    RelativeLayout layoutRecord;
    @BindView(R.id.btn_chat_add)
    Button btnChatAdd;
    @BindView(R.id.btn_chat_emo)
    Button btnChatEmo;
    @BindView(R.id.edit_msg)
    EditText editMsg;
    @BindView(R.id.btn_speak)
    Button btnSpeak;
    @BindView(R.id.btn_chat_voice)
    Button btnChatVoice;
    @BindView(R.id.btn_chat_keyboard)
    Button btnChatKeyboard;
    @BindView(R.id.btn_chat_send)
    Button btnChatSend;
    @BindView(R.id.pager_emo)
    ViewPager pagerEmo;
    @BindView(R.id.layout_emo)
    LinearLayout layoutEmo;
    @BindView(R.id.tv_picture)
    TextView tvPicture;
    @BindView(R.id.tv_camera)
    TextView tvCamera;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.layout_more)
    LinearLayout layoutMore;
    @BindView(R.id.ll_chat)
    LinearLayout llChat;
    @BindView(R.id.layout_add)
    LinearLayout layoutAdd;
    private BmobIMConversation mConversationManager;
    private LinearLayoutManager layoutManager;
    private ChatAdapter adapter;
    private Drawable[] drawable_anims;
    private BmobRecordManager recordManager;

    //申请录音权限
    private static final int GET_RECODE_AUDIO = 1;
    private static String[] PERMISSION_AUDIO = {
            Manifest.permission.RECORD_AUDIO
    };
    private Toast toast;

    @Override
    protected String title() {
        return mConversationManager.getConversationTitle();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        ButterKnife.bind(this);

        BmobIMConversation conversationEntrance = (BmobIMConversation) getBundle().getSerializable("c");
        //TODO 消息：5.1、根据会话入口获取消息管理，聊天页面
        mConversationManager = BmobIMConversation.obtain(BmobIMClient.getInstance(), conversationEntrance);
        initNaviView();
        initSwipeLayout();
        initVoiceView();
        initBottomView();



        verifyAudioPermissions(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==GET_RECODE_AUDIO){
            if (grantResults[0]== PackageManager.PERMISSION_GRANTED){
                Toast.makeText(this, "授予录音权限成功", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(this, "授予录音权限失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /*
     * 申请录音权限*/
    public static void verifyAudioPermissions(Activity activity) {
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.RECORD_AUDIO);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, PERMISSION_AUDIO,
                    GET_RECODE_AUDIO);
        }
    }


    @SuppressLint("ClickableViewAccessibility")
    private void initBottomView() {

        editMsg.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                if(motionEvent.getAction()==MotionEvent.ACTION_DOWN || motionEvent.getAction() == MotionEvent.ACTION_UP){
                    scrollToBottom();
                }

                return false;
            }
        });

        editMsg.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                scrollToBottom();
            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                if(!TextUtils.isEmpty(s)){
                    btnChatSend.setVisibility(View.VISIBLE);
                    btnChatKeyboard.setVisibility(View.GONE);
                    btnChatVoice.setVisibility(View.GONE);
                }else{
                    if(btnChatVoice.getVisibility()!=View.VISIBLE){
                        btnChatVoice.setVisibility(View.VISIBLE);
                        btnChatSend.setVisibility(View.GONE);
                        btnChatKeyboard.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }

    private void scrollToBottom() {
        layoutManager.scrollToPositionWithOffset(adapter.getItemCount()-1,0);
    }


    private void initSwipeLayout() {
        swRefresh.setEnabled(true);
        layoutManager = new LinearLayoutManager(this);
        rcView.setLayoutManager(layoutManager);
        adapter = new ChatAdapter(this, mConversationManager);
        rcView.setAdapter(adapter);
        llChat.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                llChat.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                swRefresh.setRefreshing(true);
                //自动刷新
                queryMessages(null);
            }
        });

        //下拉加载
        swRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                BmobIMMessage msg = adapter.getFirstMessage();
                queryMessages(msg);
            }
        });


        //设置RecyclerView的点击事件
        adapter.setOnRecyclerViewListener(new OnRecyclerViewListener() {
            @Override
            public void onItemClick(int position) {
                Logger.i("位置："+position);
            }

            @Override
            public boolean onItemLongClick(int position) {

                mConversationManager.deleteMessage(adapter.getItem(position));
                adapter.remove(position);
                return true;
            }
        });
    }

    /**
     * 初始化语音布局
     */
    private void initVoiceView() {
        btnSpeak.setOnTouchListener(new VoiceTouchListener());
        initVoiceAnimRes();
        initRecordManager();
    }



    private void initVoiceAnimRes() {
        drawable_anims = new Drawable[]{
                getResources().getDrawable(R.mipmap.chat_icon_voice2),
                getResources().getDrawable(R.mipmap.chat_icon_voice3),
                getResources().getDrawable(R.mipmap.chat_icon_voice4),
                getResources().getDrawable(R.mipmap.chat_icon_voice5),
                getResources().getDrawable(R.mipmap.chat_icon_voice6)

        };
    }

    private void initRecordManager() {
        recordManager = BmobRecordManager.getInstance(this);
        recordManager.setOnRecordChangeListener(new OnRecordChangeListener() {
            @Override
            public void onVolumeChanged(int value) {
                ivRecord.setImageDrawable(drawable_anims[value]);

            }

            @Override
            public void onTimeChanged(int recordTime, String localPath) {
                Logger.i("voice", "已录音长度:" + recordTime);
                //一分钟结束，发送消息
                if(recordTime>=BmobRecordManager.MAX_RECORD_TIME){

                    btnSpeak.setPressed(false);
                    btnSpeak.setClickable(false);

                    layoutRecord.setVisibility(View.INVISIBLE);
                    sendVoiceMessage(localPath,recordTime);

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            btnSpeak.setClickable(true);
                        }
                    },1000);


                }
            }
        });
    }


    /**
     * 发送语音消息
     * @param localPath
     * @param recordTime
     */
    private void sendVoiceMessage(String localPath, int recordTime) {

        BmobIMAudioMessage audio = new BmobIMAudioMessage(localPath);
        Map<String,Object> map=new HashMap<>();
        map.put("from","优酷");
        audio.setExtraMap(map);
        mConversationManager.sendMessage(audio,listener);

    }


    @Override
    public void onMessageReceive(List<MessageEvent> list) {

        //当注册页面消息监听时候，有消息（包含离线消息）到来时会回调该方法
        for (int i=0;i<list.size();i++){
            addMessage2Chat(list.get(i));
        }
    }


    @OnClick({R.id.btn_chat_add, R.id.btn_chat_emo, R.id.edit_msg, R.id.btn_speak, R.id.btn_chat_voice, R.id.btn_chat_keyboard, R.id.btn_chat_send, R.id.tv_picture, R.id.tv_camera, R.id.tv_location})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_chat_add:
                if (layoutMore.getVisibility() == View.GONE) {
                    layoutMore.setVisibility(View.VISIBLE);
                    layoutAdd.setVisibility(View.VISIBLE);
                    layoutEmo.setVisibility(View.GONE);
                    hideSoftInputView();
                } else {
                    if (layoutEmo.getVisibility() == View.VISIBLE) {
                        layoutEmo.setVisibility(View.GONE);
                        layoutAdd.setVisibility(View.VISIBLE);
                    } else {
                        layoutMore.setVisibility(View.GONE);
                    }
                }
                break;
            case R.id.btn_chat_emo:
                break;
            case R.id.edit_msg:
                break;
            case R.id.btn_speak:
                break;
            case R.id.btn_chat_voice:
                break;
            case R.id.btn_chat_keyboard:
                break;
            case R.id.btn_chat_send:
                break;
            case R.id.tv_picture:
                break;
            case R.id.tv_camera:
                break;
            case R.id.tv_location:
                break;
        }
    }


    /**
     *首次加载，可设置msg为null，下拉刷新的时候，默认取消息表的第一个msg作为刷新的起始时间点，默认按照消息时间的降序排列
     * @param msg
     */
    private void queryMessages(BmobIMMessage msg) {
        //查询指定会话的消息记录
        mConversationManager.queryMessages(msg,10, new MessagesQueryListener() {
            @Override
            public void done(List<BmobIMMessage> list, BmobException e) {
                swRefresh.setRefreshing(false);
                if(e==null){
                    if(null!=list&&list.size()>0){
                        adapter.addMessages(list);
                        layoutManager.scrollToPositionWithOffset(list.size()-1,0);

                    }
                }else{
                    toast(e.getMessage()+"("+e.getErrorCode()+")");
                }
            }
        });
    }


    class VoiceTouchListener implements View.OnTouchListener{
        @Override
        public boolean onTouch(View v, MotionEvent motionEvent) {

            switch(motionEvent.getAction()){
                case MotionEvent.ACTION_DOWN:
                    if(Util.checkSdCard()){
                        toast("发送语音需要sdcard支持");
                        return false;
                    }

                    try {
                        v.setPressed(true);
                        layoutRecord.setVisibility(View.VISIBLE);
                        tvVoiceTips.setText(getString(R.string.voice_cancel_tips));
                        //开始录音
                        recordManager.startRecording(mConversationManager.getConversationId());

                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    return true;
                case MotionEvent.ACTION_MOVE:

                    if(motionEvent.getY()<0){
                        tvVoiceTips.setText(getString(R.string.voice_cancel_tips));
                        tvVoiceTips.setTextColor(Color.RED);
                    }else{
                        tvVoiceTips.setText(getString(R.string.voice_up_tips));
                        tvVoiceTips.setTextColor(Color.WHITE);
                    }

                    return true;
                case MotionEvent.ACTION_UP:
                    v.setPressed(false);
                    layoutRecord.setVisibility(View.INVISIBLE);
                    try {

                        if(motionEvent.getY()<0){
                            recordManager.cancelRecording();
                        }else{
                            int recordTime = recordManager.stopRecording();
                            if(recordTime>1){
                                sendVoiceMessage(recordManager.getRecordFilePath(mConversationManager.getConversationId()),recordTime);
                            }else{
                                layoutRecord.setVisibility(View.GONE);
                                showShortToast().show();
                            }
                        }


                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    return true;

                default:
                    return false;
            }

        }
    }

    private Toast showShortToast() {

        if(toast==null){
            toast = new Toast(this);
        }

        View view = LayoutInflater.from(this).inflate(R.layout.include_chat_voice_short, null);
        toast.setView(view);
        toast.setGravity(Gravity.CENTER,0,0);
        toast.setDuration(Toast.LENGTH_SHORT);
        return toast;
    }


    /**
     * 消息发送监听器
     */
    public MessageSendListener listener = new MessageSendListener() {

        @Override
        public void onProgress(int i) {
            super.onProgress(i);
        }

        @Override
        public void onStart(BmobIMMessage bmobIMMessage) {
            super.onStart(bmobIMMessage);
            adapter.addMessage(bmobIMMessage);
            editMsg.setText("");
            scrollToBottom();
        }

        @Override
        public void done(BmobIMMessage bmobIMMessage, BmobException e) {

            adapter.notifyDataSetChanged();
            editMsg.setText("");
            scrollToBottom();
            if(e==null){
                toast(e.getMessage());
            }

        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (layoutMore.getVisibility() == View.VISIBLE) {
                layoutMore.setVisibility(View.GONE);
                return false;
            } else {
                return super.onKeyDown(keyCode, event);
            }
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onResume() {
        //锁屏期间的收到的未读消息需要添加到聊天界面中
        addUnReadMessage();
       //添加页面消息监听
        BmobIM.getInstance().addMessageListHandler(this);
        //有可能锁屏期间，在聊天界面出现通知栏，这个时候需要清除通知
        BmobNotificationManager.getInstance(this).cancelNotification();

        super.onResume();
    }

    private void addUnReadMessage() {
        List<MessageEvent> cacheList = BmobNotificationManager.getInstance(this).getNotificationCacheList();
        if(cacheList.size()>0){
            int size=cacheList.size();
            for (int i=0;i<size;i++){
                MessageEvent event=cacheList.get(i);
                addMessage2Chat(event);
            }
        }
        scrollToBottom();
    }

    /**
     * 添加消息到聊天界面
     */
    private void addMessage2Chat(MessageEvent event) {
        BmobIMMessage msg = event.getMessage();
        if(mConversationManager!=null
                &&event!=null
                &&mConversationManager.getConversationId().equals(event.getConversation().getConversationId())
                &&!msg.isTransient()){
            if(adapter.findPosition(msg)<0){
                adapter.addMessage(msg);
                //更新该会话下面的已读状态
                mConversationManager.updateReceiveStatus(msg);
            }
            scrollToBottom();

        }else{

        }
    }

    @Override
    protected void onPause() {
        //移除页面消息监听
        BmobIM.getInstance().removeMessageListHandler(this);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        //清理资源
        if(recordManager!=null){
            recordManager.clear();
        }

        //更新会话的所有消息为已读状态
        if(mConversationManager!=null){
            mConversationManager.updateLocalCache();
        }
        hideSoftInputView();
        super.onDestroy();
    }
}
